package cn.cvs.controller;

import cn.cvs.pojo.Supplier;
import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.StorageRecordService;
import cn.cvs.service.SupplierService;
import cn.cvs.utils.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/supplier")
public class SupplierController {
    @Resource
    private SupplierService supplierService;
    @Resource
    private StorageRecordService storageRecordService;

    @RequestMapping("/list")
    public String list(Model model, String querySupCode, String querySupName, @RequestParam(defaultValue = "1", required = false) Integer pageIndex) {
        //查询供货商数量
        int pageCounts = supplierService.getSupplierByWhere(querySupCode, querySupName);
        //用户每页显示数量
        int pageSize = 5;
        //总页数
        PageSupport p = new PageSupport();
        p.setCurrentPageNo(pageIndex);
        p.setPageSize(pageSize);
        p.setTotalCount(pageCounts);
        int totalPageCount = p.getTotalPageCount();
        //控制首页和尾页
        if (pageIndex > totalPageCount) {
            pageIndex = totalPageCount;
            throw new RuntimeException("页码不正确");
        }

        List<Supplier> supplierList = supplierService.getSupplierByCodeAndName(querySupCode, querySupName, pageIndex, pageSize);
        //存储供货商集合
        model.addAttribute("supplierList", supplierList);
        //查询的供货商名
        model.addAttribute("querySupName", querySupName);
        //查询的供货商编号
        model.addAttribute("querySupCode", querySupCode);
        //总页数
        model.addAttribute("totalPageCount", totalPageCount);
        //查询总数量
        model.addAttribute("totalCount", pageCounts);
        //当前页码
        model.addAttribute("currentPageNo", pageIndex);

        return "supplier/list";
    }


    @RequestMapping("/del")
    @ResponseBody
    public Object del(Integer proid) {
        Map<String, Object> map = new HashMap<>();
        System.out.println("proid-===:" + proid);
        if (proid != null) {
            //根据供货商id查询该供货商下是否有商品
            int count = 0;
            int a = -1;
            try {
                count = storageRecordService.getStorageRecordBySupplierId(proid);
                if (count > 0) {
                    map.put("delResult", count);
                } else {
                    a = supplierService.delSupplier(proid);
                    if (a > 0) {
                        map.put("delResult", "true");
                    } else {
                        map.put("delResult", "false");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                map.put("delResult", "false");
            }

        } else {
            map.put("delResult", "notexist");
        }

        return map;
    }

    @RequestMapping("/toAdd")
    public String toAdd() {
        return "supplier/add";
    }

    @RequestMapping("/add")
    public String add(Model model, Supplier supplier, HttpSession session, MultipartFile[] attachs) {

        String companyLicPic = "";
        String orgCodePic = "";
        String errorInfo = "";

        //定义文件存储路径
        String path = session.getServletContext().getRealPath("statics" + File.separator + "upload");
        for (int i = 0; i < attachs.length; i++) {
            System.out.println("进入文件上传");
            MultipartFile pic = attachs[i];
            //判断是否为空
            if (!pic.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadOcError";
                }
                //获取原文件名
                String oldFileName = pic.getOriginalFilename();
                //获取原文件后缀
                String suffix = FilenameUtils.getExtension(oldFileName);
                //设置文件上传大小
                int fileSize = 500000;
                //判断文件大小
                if (pic.getSize() > fileSize) {
                    model.addAttribute(errorInfo, "上传大小不得超过500KB");
                    System.out.println("上传太大");
                    return "supplier/add";
                    //判断文件格式
                } else if (suffix.equalsIgnoreCase("jpg") ||
                        suffix.equalsIgnoreCase("png") ||
                        suffix.equalsIgnoreCase("jpeg") ||
                        suffix.equalsIgnoreCase("pneg")) {

                    //给文件重命名
                    String newFileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "." + suffix;
                    File file = new File(path);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    //保存
                    try {
                        pic.transferTo(new File(file, newFileName));
                        System.out.println("上传成功！");
                    } catch (IOException e) {
                        e.printStackTrace();
                        model.addAttribute(errorInfo, "上传失败");
                        System.out.println("上传失败");
                        return "supplier/add";
                    }
                    //存储文件路径
                    if (i == 0) {
                        companyLicPic = File.separator + "statics" + File.separator + "upload" + File.separator + newFileName;
                    } else if (i == 1) {
                        orgCodePic = File.separator + "statics" + File.separator + "upload" + File.separator + newFileName;
                    }
                    System.out.println("idpicpath" + companyLicPic);
                    System.out.println("workpicpath" + orgCodePic);

                } else {
                    model.addAttribute(errorInfo, "上传文件格式不正确");
                    System.out.println("上传文件格式不正确");
                    return "supplier/add";
                }

            }
        }

        supplier.setCreatedTime(new Date());
        supplier.setCreatedUserId(((SysUser) session.getAttribute("userSession")).getId());
        supplier.setCompanyLicPicPath(companyLicPic);
        supplier.setOrgCodePicPath(orgCodePic);
        int a = supplierService.addSupplier(supplier);
        if (a > 0) {
            return "redirect:/sys/supplier/list";
        } else {
            return "supplier/add";
        }

    }

    @RequestMapping("/toUpdate/{supId}")
    public String toUpdate(@PathVariable Integer supId,Model model){
        Supplier supplier=supplierService.getSupplierById(supId);
        model.addAttribute("supplier",supplier);
        return "supplier/update";
    }
    @RequestMapping("/update")
    public String update(Supplier supplier,HttpSession session){
        supplier.setUpdatedTime(new Date());
        supplier.setUpdatedUserId(((SysUser) session.getAttribute("userSession")).getId());
        int a=supplierService.updSupplierById(supplier);
        if(a>0){
            return "redirect:/sys/supplier/list";
        }else{
            return "supplier/update";
        }

    }

    @RequestMapping("/view/{supId}")
    public String view(@PathVariable Integer supId,Model model){
        Supplier supplier=supplierService.getSupplierById(supId);
        model.addAttribute("supplier",supplier);
        return "supplier/view";
    }

    @RequestMapping("/simpleList")
    @ResponseBody
    public Object simpleList(){
        List<Supplier> supplierList=null;
        try {
            supplierList=supplierService.getSupplierList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return supplierList;
    }



}
